﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WP09S03_OfficeTracking.Controller;
using WP09S03_OfficeTracking.DAL;
using WP09S03_OfficeTracking.UserControls;

namespace WP09S03_OfficeTracking
{
    public partial class FrmEquipmentIssue : WP09S03_OfficeTracking.ParentClass.ParentForm
    {
        TransactionController tran = new TransactionController();
        public FrmEquipmentIssue()
        {
            InitializeComponent();
            CtrlItem item = new CtrlItem();
        }       

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string emailContent = "<p>Dear Sir / Madam,</p><p style='margin-left:40px'>This is to confirm that you have borrowed the following item(s) from our company</p><p style='margin-left:40px'>ItemDetailID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SerialNo&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ItemName&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Loan Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Due Date</p><p style='margin-left:40px'>---------------------------------------------------------------------------------------------</p>";
                string employeeID = this.txtEmployeeID.Text.Trim();
                if (employeeID == "")
                {
                    SetMessage("Invalid EmployeeID.");
                    return;
                }

                EmployeController empCtrl = new EmployeController();
                DSEmployee.EmployeeDataTable table = empCtrl.GetEmployeesByID(employeeID);

                if (table.Rows.Count == 0)
                {
                    SetMessage("Invalid EmployeeID.");
                    return;
                }
                if (this.dgvData.Rows.Count == 1)
                {
                    SetMessage("No Item Information.");
                    return;
                }

                if (Convert.ToDateTime(this.dtpReturnDate.Text) < DateTime.Now.Date)
                {
                    SetMessage("Invalid Return Date.");
                    return;
                }

                DataTable data = new DataTable();
                data.Columns.Add("ItemDetailID", typeof(System.String));
                data.Columns.Add("Quantity", typeof(System.Int32));
                data.Columns.Add("UsedEndTime", typeof(System.DateTime));

                for (int i = 0; i < this.dgvData.RowCount - 1; i++)
                {
                    DataRow row = data.NewRow();
                    row[0] = this.dgvData.Rows[i].Cells[1].Value.ToString();
                    row[1] = Convert.ToInt32(this.dgvData.Rows[i].Cells[6].Value.ToString());
                    row[2] = Convert.ToDateTime(this.dtpReturnDate.Text);
                    data.Rows.Add(row);
                    emailContent += String.Format("<p style='margin-left:40px'>{0}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{1}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{2}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{4}</p>", this.dgvData.Rows[i].Cells[1].Value.ToString(), this.dgvData.Rows[i].Cells[2].Value.ToString(), this.dgvData.Rows[i].Cells[3].Value.ToString(), DateTime.Now.ToString(), Convert.ToDateTime(this.dtpReturnDate.Text));
                }
                bool result = tran.IssueTransactionBookAndEquipment(employeeID, data);
                if (result)
                {
                    clearTransactionInfo();
                    Email email = new Email();
                    email.MailTo = table.Rows[0][table.EmailColumn].ToString();
                    email.MailSubject = "Confirmation of Item(s) Issued";
                    email.MailBody = emailContent + "<p></p><p></p><p>Best Regards,</p><p>Administrator</p><p style='margin-left:40px'>This is a system generated email, please do not reply.</p>";
                    email.Send();
                    SetMessage("Transaction is successful.");
                }
                else
                {
                    SetMessage("Transaction is fail.");
                }
            }
            catch(Exception err)
            {
                SetMessage("Transaction is fail." + err.Message);
                CatchError(err);
            }
        }

        private void btnItemSelect_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.ctrlEquipments.dgvData.SelectedRows.Count != 0)
                {
                    for (int i = 0; i < this.ctrlEquipments.dgvData.SelectedRows.Count; i++)
                    {
                        if (!Exist(this.ctrlEquipments.dgvData.SelectedRows[i].Cells[1].Value.ToString()))
                        {
                            DataGridViewRow row = new DataGridViewRow();
                            row.CreateCells(this.dgvData);
                            row.Cells[0].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[0].Value.ToString();
                            row.Cells[1].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[1].Value.ToString();
                            row.Cells[2].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[2].Value.ToString();
                            row.Cells[3].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[3].Value.ToString();
                            row.Cells[4].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[4].Value.ToString();
                            row.Cells[5].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[5].Value.ToString();
                            row.Cells[6].Value = "1";
                            row.Cells[7].Value = this.ctrlEquipments.dgvData.SelectedRows[i].Cells[6].Value.ToString();

                            this.dgvData.Rows.Add(row);
                        }
                    }
                    isEnableSubmit();
                    SetMessage("");
                }
                else
                {
                    SetMessage("Pleaes select Item information.");
                }

            }
            catch (Exception err)
            {
                CatchError(err);
            }
        }

        private void btnEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.employeeUControl.dataGridViewEmployees.SelectedRows.Count != 0)
                {
                    this.txtEmployeeID.Text = this.employeeUControl.dataGridViewEmployees.SelectedRows[0].Cells[0].Value.ToString();
                    isEnableSubmit();
                    SetMessage("");
                    tcSearch.SelectedTab = tcSearch.TabPages[1];
                }
                else
                {
                    SetMessage("Please select employee.");
                }

            }
            catch (Exception err)
            {
                CatchError(err);
            }
        }

        private void clearTransactionInfo()
        {
            this.txtEmployeeID.Text = "";
            this.dgvData.Rows.Clear();
            this.ctrlEquipments.BindData_DGV();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dgvData.Rows.Count > 1)
                {
                    if (!this.dgvData.CurrentRow.IsNewRow)
                    {
                        this.dgvData.Rows.RemoveAt(this.dgvData.CurrentRow.Index);
                    }
                }
                isEnableSubmit();
            }
            catch (Exception err)
            {
                CatchError(err);
            }
        }
       
        private bool Exist(string itemDetailID)
        {
            foreach (DataGridViewRow row in this.dgvData.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    if (row.Cells[1].Value.ToString() == itemDetailID)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void FrmEquipmentIssue_Load(object sender, EventArgs e)
        {
            btnItemSelect.Enabled = false;
            this.btnEmployee.Enabled = false;
            isEnableSubmit();
            ctrlEquipments.dgvData.SelectionChanged += dgvData_ItemSelectionChanged;
            employeeUControl.dataGridViewEmployees.SelectionChanged += dgvData_EmployeeSelectionChanged;

            this.dtpReturnDate.Value = DateTime.Now.AddDays(Properties.Settings.Default.DefaultLeaseDate);


        }

        private void dgvData_ItemSelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.ctrlEquipments.dgvData.SelectedRows.Count > 0)
                {
                    btnItemSelect.Enabled = true;
                }
                else
                {
                    btnItemSelect.Enabled = false;
                }

            }
            catch (Exception err)
            {
                CatchError(err);
            }
        }

        private void dgvData_EmployeeSelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.employeeUControl.dataGridViewEmployees.SelectedRows.Count > 0)
                {
                    this.btnEmployee.Enabled = true;
                }
                else
                {
                    this.btnEmployee.Enabled = false;
                }
            }
            catch (Exception err)
            {
                CatchError(err);
            }
        }

        private void isEnableSubmit()
        {
            if (this.dgvData.Rows.Count > 1 && this.txtEmployeeID.Text.Trim() != "")
            {
                this.btnDelete.Enabled = true;
                this.btnSubmit.Enabled = true;
            }
            else
            {
                this.btnDelete.Enabled = false;
                this.btnSubmit.Enabled = false;
            }
        }
    }
}
